//
//  CYSelectCardView.m
//  cyjf
//
//  Created by tauCross on 2017/5/15.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYSelectCardView.h"

#import "CYSelectCardCell.h"
#import "CYSelectCardAddCell.h"

#import <NIMutableTableViewModel.h>
#import <NICellFactory.h>



@interface CYSelectCardView ()<UITableViewDelegate>

@property(nonatomic, strong)UIButton *maskButton;
@property(nonatomic, strong)UIView *contentView;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NIMutableTableViewModel *tableModel;
@property(nonatomic, strong)NICellObject *addCell;

@end


@implementation CYSelectCardView

- (instancetype)initWithCardList:(NSArray *)cardList title:(NSString *)title hasAddButton:(BOOL)hasAddButton
{
    self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    if(self)
    {
        [self loadDataWithCardList:cardList hasAddButton:hasAddButton];
        [self loadUIWithTitle:title];
        @weakify(self);
        [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:CYHideAllCustomViewOnWindowNotification object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(id x) {
            @strongify(self);
            [self closeAction];
        }];
    }
    return self;
}

- (void)loadDataWithCardList:(NSArray *)cardList hasAddButton:(BOOL)hasAddButton
{
    NSMutableArray *cells = [NSMutableArray array];
    for(CYDataAPIBankCardModel *apiModel in cardList)
    {
        CYSelectCardCellObject *cell = [CYSelectCardCellObject objectWithCellClass:[CYSelectCardCell class]];
        cell.hasLimit = hasAddButton;
        cell.apiModel = apiModel;
        cell.bankIcon = SAFE_STRING(apiModel.bankIcon);
        cell.bankName = SAFE_STRING(apiModel.bankName);
        cell.cardNumber = SAFE_STRING(apiModel.bankCardNo).length < 4 ? @"****" : [SAFE_STRING(apiModel.bankCardNo) substringFromIndex:SAFE_STRING(apiModel.bankCardNo).length - 4];
        NSString *limitTimes = SAFE_STRING(apiModel.limitTimesStr);
        NSString *limitDay = SAFE_STRING(apiModel.limitDayStr);
        cell.onceLimit = ([limitTimes isEqualToString:@"0"] || (limitTimes.length == 0)) ? @"单笔无限额" : [NSString stringWithFormat:@"单笔限额：%@万", limitTimes];
        cell.totalLimit = ([limitDay isEqualToString:@"0"] || (limitDay.length == 0)) ? @"单日无限额" : [NSString stringWithFormat:@"单日限额：%@万", limitDay];
        [cells addObject:cell];
    }
    if(hasAddButton)
    {
        self.addCell = [NICellObject objectWithCellClass:[CYSelectCardAddCell class]];
        [cells addObject:self.addCell];
    }
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
}

- (void)loadUIWithTitle:(NSString *)title
{
    self.maskButton = [[UIButton alloc] initWithFrame:self.bounds];
    self.maskButton.backgroundColor = HEXCOLORA(@"000000", 0.5);
    self.maskButton.alpha = 0;
    [self.maskButton addTarget:self action:@selector(onMaskButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.maskButton];
    
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height, self.width, self.height / 2)];
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.contentView];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 55, 50)];
    [closeButton addTarget:self action:@selector(onCloseButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setImage:CYImage(@"public_nav_close") forState:UIControlStateNormal];
    [self.contentView addSubview:closeButton];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = [UIFont systemFontOfSize:16];
    titleLabel.textColor = HEXCOLOR(@"444444");
    [titleLabel sizeToFit];
    titleLabel.centerX = self.contentView.width / 2;
    titleLabel.centerY = 25;
    [self.contentView addSubview:titleLabel];
    
    UIView *line = [UIView cy_lineWithColor:HEXCOLOR(@"ECECEC")];
    line.width = self.contentView.width;
    line.height = 1 / SCREEN_SCALE;
    line.bottom = 50;
    line.left = 0;
    [self.contentView addSubview:line];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, line.bottom, self.contentView.width, self.contentView.height - line.bottom) style:UITableViewStylePlain];
    self.tableView.tableHeaderView = [[UIView alloc] init];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 23)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self.tableModel;
    [self.contentView addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
}

#pragma mark - Actions
- (void)closeAction
{
    @weakify(self);
    [UIView animateWithDuration:0.25
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         @strongify(self);
                         self.maskButton.alpha = 0;
                         self.contentView.top = self.height;
                     }
                     completion:^(BOOL finished) {
                         @strongify(self);
                         [self removeFromSuperview];
                     }];
}

- (void)show
{
    [[[UIApplication sharedApplication] keyWindow] addSubview:self];
    @weakify(self);
    [UIView animateWithDuration:0.25
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         @strongify(self);
                         self.maskButton.alpha = 1;
                         self.contentView.bottom = self.height;
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

- (void)addAction
{
    if(self.addCardAction)
    {
        self.addCardAction();
    }
    [self closeAction];
}

- (void)selecteActionWithApiModel:(CYDataAPIBankCardModel *)apiModel
{
    if(self.completeAction)
    {
        self.completeAction(apiModel);
    }
    [self closeAction];
}

#pragma mark - Control Events
- (void)onMaskButtonTouchUpInside
{
    if(self.addCell == nil)
    {
        
    }
    else
    {
        [MobClick event:UM_EVENT_0037];
    }
    [self closeAction];
}

- (void)onCloseButtonTouchUpInside
{
    if(self.addCell == nil)
    {
        
    }
    else
    {
        [MobClick event:UM_EVENT_0037];
    }
    [self closeAction];
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [NICellFactory tableView:tableView heightForRowAtIndexPath:indexPath model:self.tableModel];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NICellObject *cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.addCell)
    {
        [MobClick event:UM_EVENT_0039];
        [self addAction];
        return;
    }
    if([cellObject isKindOfClass:[CYSelectCardCellObject class]])
    {
        if(self.addCell == nil)
        {
            
        }
        else
        {
            [MobClick event:UM_EVENT_0038];
        }
        [self selecteActionWithApiModel:[(CYSelectCardCellObject *)cellObject apiModel]];
        return;
    }
}

@end
